import json
import sqlite3
from typing import Any


class Storage:
    def __init__(self, path: str):
        self.__conn = sqlite3.connect(path)
        self.__cursor = self.__conn.cursor()

        self.__execute("CREATE TABLE IF NOT EXISTS STORAGE (KEY TEXT PRIMARY KEY NOT NULL, VALUE TEXT NOT NULL);")

    def set(self, key: str, value: Any):
        self.__execute(f"REPLACE INTO STORAGE (KEY, VALUE) VALUES ('{key}', '{json.dumps(value)}');")

    def get(self, key: str):
        cursor = self.__cursor.execute(f"SELECT VALUE FROM STORAGE WHERE KEY = '{key}';")
        for row in cursor:
            return json.loads(row[0])

    def getValues(self):
        cursor = self.__cursor.execute("SELECT * FROM STORAGE;")
        return [json.loads(row[1]) for row in cursor]

    def save(self):
        self.__conn.commit()

    def close(self):
        self.save()
        self.__conn.close()

    def __execute(self, sql: str):
        self.__cursor.execute(sql)
